const DEFULT_AUTO_REPLY = '功能正在开发中~';
const config = require('./config.js');
module.exports = class extends think.Controller {
	constructor(ctx) {
		super(ctx);
		this.sgoods = this.appModel("goods", "sales");
		this.transfer = this.model("taoke/transfer");
		this.order = this.model("taoke/order");
		this.qrcode = this.model("taoke/qrcode");
		this.queue = this.model("taoke/queue");
		this.goods = this.model("taoke/goods");
		this.wxuser = this.model("weixin/user");
		this.conf = this.model("weixin/config");
		this.msg = this.model("weixin/msg");
		this.msg_reply = this.model("weixin/msg_reply");
		this.user = this.model("system/user");
		this.asset = this.model("system/asset");
		this.score = this.model("system/score");
		this.agency = this.model("system/agency");
		this.appid = think.config('setup.weixinAppid');

	}
	indexAction() {
		const echostr = this.get('echostr');
		return this.body = echostr;
	}
	// 关键词消息回复
	async textAction() {
		try {

			const message = this.post();
			console.log(message);

			const key = message.Content.trim();
			const openid = message.FromUserName;

			const taokeReg = `.*(([${think.config("setup.taokeSplit")}]{1}([A-Za-z0-9]{11,})[${think.config("setup.taokeSplit")}]{1})|(http)).*`;

			let reg = new RegExp(taokeReg);

			let wxuser = await this.wxuser.where({
				openid: openid
			}).find();

			if(think.isEmpty(wxuser.user_id)) {
				const weixin = await this.conf.where({
					appid: this.appid
				}).find();

				let api = await this.wechatApi(weixin.id);

				let userInfo = await api.getUser(openid);
				userInfo.wxid = weixin.id;
				await this.wxuser.bindUser(wxuser, userInfo);
				wxuser = await this.wxuser.where({
					openid: openid
				}).find();
				//return this.success(`未绑定平台用户,请先绑定:\nhttp://huitao.huihoor.net/app/wxmp/user/login`);
			}
			let msg = "";
			let messageType = think.config("setup.weixinMessageType");

			if(reg.test(key)) {

				let result = await this.transfer.getResult(wxuser.user_id, key);
				console.log(result);
				if(!result) {
					msg = "该宝贝没有优惠策略";
				} else {

					msg = think.getInstance(result, config.transfer.tmpl[messageType]);

				}
				return this.success(msg);

			}

			//绑单

			if(/(^([0-9]{10,25})$)/.test(key)) {

				let data = await this.order.bindOrders(key, wxuser.user_id);
				msg = data.errmsg;
				return this.success(msg);

			}

			if(key == '签到') {

				let data = await this.score.attend(wxuser.user_id);
				msg = think.getInstance(data.data, config.attend.tmpl[data.code]);
				return this.success(msg);

			}

			if(key == '提现') {

				let data = await this.asset.getcash(wxuser.user_id, 'wxmp');
				msg = think.getInstance(data.data, config.getcash.tmpl[data.code]);
				return this.success(msg);

			}

			if(key == '余额') {

				let data = await this.asset.getbalance(wxuser.user_id);
				msg = think.getInstance(data, config.balance.tmpl);
				return this.success(msg);

			}
			if(key == '帮助') {
				msg = think.getInstance(config.help.data, config.help.tmpl[messageType]);
				return this.success(msg);

			}

			if(key == '指令') {
				msg = think.getInstance(config.directive.data, config.directive.tmpl);
				return this.success(msg);

			}

			if(key == '邀请查询') {
				let data = await this.asset.getInvite(wxuser.user_id);
				msg = think.getInstance(data, config.invite.tmpl);
				return this.success(msg);

			}

			if(/^(买|找|查|搜).*/.test(key)) {
				let keyword = key.slice(1);
				let data = await this.goods.search(keyword);
				msg = think.getInstance(data, config.search.tmpl);
				return this.success(msg);

			}
			if(key == '推广') {
				let data = await this.qrcode.share(wxuser.user_id);
				msg = think.getInstance(data, config.share.tmpl);
				return this.success(msg);

			}

			if(key == '用户号') {

				return this.success(`用户号 ${message.FromUserName}`);

			}

			let msgid = await this.msg.add({
				user_id: wxuser.user_id,
				openid: wxuser.openid,
				nickname: wxuser.nickname,
				type: 'text',
				content: think.emojiFilter(key),
				create_time: new Date().valueOf(),
				wxid: wxuser.wxid

			});

			return this.success("该内容尚无自动回复，请确认输入的指令正确，搜索商品关键词或标题前加“买/找/查/搜,例如:买XXXXXX");
		} catch(e) {
			console.log(e)
		}

	}

	// 事件关注
	async eventAction() {
		try {

			const message = this.post();
			console.log(JSON.stringify(message));
			switch(message.Event) {
				case 'subscribe': // 首次关注
					let user = await this.wxuser.where({
						openid: message.FromUserName
					}).find();
					const weixin = await this.conf.where({
						appid: this.appid
					}).find();

					let api = await this.wechatApi(weixin.id);

					let userInfo = await api.getUser(message.FromUserName);

					if(think.isEmpty(user)) {

						if(!think.isEmpty(message.EventKey)) {
							let qrcodeId = message.EventKey.split("_")[1];

							let qrcode = await this.qrcode.where({
								id: qrcodeId
							}).find();
							let agencyId = await this.agency.where({
								user_id: qrcode.user_id
							}).getField("id", true);
							userInfo.agency_id = agencyId;
							user.agency_id = agencyId;

							console.log(userInfo);

						}
					}

					if(think.isEmpty(user.user_id)) {

						userInfo.wxid = weixin.id;
						await this.wxuser.bindUser(user, userInfo);
					}

					let messageType = think.config("setup.weixinMessageType");
					let reply = think.getInstance(config.help.data, config.help.tmpl[messageType]);

					return this.success(reply);

					break;
				case 'unsubscribe': // 取消关注
					// todo
					break;
				case 'CLICK': // click事件坚挺
					if(message.EventKey == '快捷指令') {
						let msg = think.getInstance(config.directive.data, config.directive.tmpl);
						return this.success(msg);

					}
					// todo
					break;
				case 'SCAN': // 扫码事件监听

					break;
				default:
					console.log(message);

					break;
			}
			return this.success();
		} catch(e) {
			console.log(e);
		}

	}
	__call() {
		return this.success(DEFULT_AUTO_REPLY);
	}

};